from fastapi import APIRouter, Depends, HTTPException, status, Query, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional, Union

from app.core.database import get_db
from app.core.deps import get_current_user, get_tenant_id
from app.schemas.user import (
    UserQuery, UserVO, UserForm, UserInfoVO, ResetPwdForm, UserInfo
)
from app.schemas.system import DeptTreeVO
from app.schemas.role import RoleVO
from app.models.user import User
from app.services.user import user_service
# from app.services.dept import dept_service
# from app.services.role import role_service
from app.utils.response import ResponseUtil

router = APIRouter()


@router.get("/list", summary="查询用户列表", response_model=List[UserVO])
async def list_user(
    query: UserQuery = Depends(),
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询用户列表"""
    users = await user_service.get_user_list(db, query=query, tenant_id=tenant_id)
    return users


@router.get("/optionselect", summary="通过用户ids查询用户", response_model=List[UserVO])
async def option_select(
    userIds: str = Query(..., description="用户ID列表，逗号分隔"),
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """通过用户ids查询用户"""
    user_id_list = [int(uid.strip()) for uid in userIds.split(',') if uid.strip()]
    users = await user_service.get_users_by_ids(db, user_ids=user_id_list, tenant_id=tenant_id)
    return users


@router.get("/{userId}", summary="获取用户详情", response_model=UserInfoVO)
async def get_user(
    userId: Union[str, int],
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取用户详情"""
    if userId == "":
        # 新增用户时的空ID，返回空的用户信息用于表单初始化
        return UserInfoVO(
            user=None,
            roles=[],
            roleIds=[],
            posts=[],
            postIds=[],
            roleGroup="",
            postGroup=""
        )

    user_info = await user_service.get_user_info(db, user_id=int(userId), tenant_id=tenant_id)
    if not user_info:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    return user_info


@router.post("", summary="新增用户")
async def add_user(
    data: UserForm,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """新增用户"""
    # 检查用户名是否已存在
    existing_user = await user_service.get_by_username(db, username=data.userName)
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )

    new_user = await user_service.create_user(db, user_data=data, tenant_id=tenant_id)
    return ResponseUtil.success(data={"userId": new_user.user_id}, message="用户创建成功")


@router.put("", summary="修改用户")
async def update_user(
    data: UserForm,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """修改用户"""
    updated_user = await user_service.update_user(
        db,
        user_id=int(data.userId),
        user_data=data,
        tenant_id=tenant_id
    )
    if not updated_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    return ResponseUtil.success(message="用户更新成功")


@router.delete("/{userId}", summary="删除用户")
async def del_user(
    userId: Union[str, int],
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """删除用户"""
    if isinstance(userId, str) and ',' in userId:
        # 批量删除
        user_ids = [int(uid.strip()) for uid in userId.split(',') if uid.strip()]
    else:
        user_ids = [int(userId)]

    for user_id in user_ids:
        if user_id == current_user.user_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能删除当前登录用户"
            )

    deleted_count = await user_service.delete_users(db, user_ids=user_ids, tenant_id=tenant_id)
    return ResponseUtil.success(message=f"成功删除 {deleted_count} 个用户")


@router.put("/resetPwd", summary="用户密码重置")
async def reset_user_pwd(
    data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """用户密码重置"""
    user_id = data.get("userId")
    password = data.get("password")

    if not user_id or not password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户ID和密码不能为空"
        )

    await user_service.reset_password(db, user_id=user_id, password=password, tenant_id=tenant_id)
    return ResponseUtil.success(message="密码重置成功")


@router.put("/changeStatus", summary="用户状态修改")
async def change_user_status(
    data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """用户状态修改"""
    user_id = data.get("userId")
    status_value = data.get("status")

    if user_id is None or status_value is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户ID和状态不能为空"
        )

    if user_id == current_user.user_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能修改当前登录用户的状态"
        )

    await user_service.change_status(db, user_id=user_id, status=status_value, tenant_id=tenant_id)
    return ResponseUtil.success(message="状态修改成功")


@router.get("/profile", summary="查询用户个人信息", response_model=UserInfoVO)
async def get_user_profile(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """查询用户个人信息"""
    user_info = await user_service.get_user_info(db, user_id=current_user.user_id, tenant_id=current_user.tenant_id)
    return user_info


@router.put("/profile", summary="修改用户个人信息")
async def update_user_profile(
    data: UserForm,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """修改用户个人信息"""
    # 只允许修改个人信息，不能修改角色等权限相关信息
    profile_data = UserForm(
        userId=str(current_user.user_id),
        userName=current_user.user_name,  # 用户名不允许修改
        nickName=data.nickName,
        email=data.email,
        phonenumber=data.phonenumber,
        sex=data.sex,
        status=current_user.status,
        remark=data.remark,
        postIds=[],  # 个人资料修改不涉及岗位
        roleIds=[]   # 个人资料修改不涉及角色
    )

    updated_user = await user_service.update_user(
        db,
        user_id=current_user.user_id,
        user_data=profile_data,
        tenant_id=current_user.tenant_id
    )
    return ResponseUtil.success(message="个人信息修改成功")


@router.put("/profile/updatePwd", summary="用户密码重置")
async def update_user_pwd(
    data: dict,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """用户密码重置"""
    old_password = data.get("oldPassword")
    new_password = data.get("newPassword")

    if not old_password or not new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="原密码和新密码不能为空"
        )

    await user_service.change_password(
        db,
        user_id=current_user.user_id,
        old_password=old_password,
        new_password=new_password
    )
    return ResponseUtil.success(message="密码修改成功")


@router.post("/profile/avatar", summary="用户头像上传")
async def upload_avatar(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """用户头像上传"""
    # TODO: 实现文件上传逻辑
    avatar_url = await user_service.upload_avatar(db, user_id=current_user.user_id, file=file)
    return ResponseUtil.success(data={"imgUrl": avatar_url}, message="头像上传成功")


@router.get("/authRole/{userId}", summary="查询授权角色")
async def get_auth_role(
    userId: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询授权角色"""
    auth_info = await user_service.get_auth_role(db, user_id=userId, tenant_id=tenant_id)
    return ResponseUtil.success(data=auth_info)


@router.put("/authRole", summary="保存授权角色")
async def update_auth_role(
    userId: str = Query(...),
    roleIds: str = Query(...),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """保存授权角色"""
    role_id_list = [int(rid.strip()) for rid in roleIds.split(',') if rid.strip()]
    await user_service.update_user_roles(
        db,
        user_id=int(userId),
        role_ids=role_id_list,
        tenant_id=tenant_id
    )
    return ResponseUtil.success(message="角色授权成功")


@router.get("/list/dept/{deptId}", summary="查询当前部门的所有用户信息", response_model=List[UserVO])
async def list_user_by_dept_id(
    deptId: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询当前部门的所有用户信息"""
    users = await user_service.get_users_by_dept(db, dept_id=deptId, tenant_id=tenant_id)
    return users


@router.get("/deptTree", summary="查询部门下拉树结构", response_model=List[DeptTreeVO])
async def dept_tree_select(
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询部门下拉树结构"""
    dept_tree = await dept_service.get_dept_tree(db, tenant_id=tenant_id)
    return dept_tree


@router.get("/getInfo", summary="获取用户详细信息", response_model=UserInfo)
async def get_info(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """获取用户详细信息"""
    user_info = await user_service.get_current_user_info(db, user=current_user)
    return user_info